<template>
  <div class="sparePartDetails">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      showStep
      showTopTitle
      :creatInfo="formData"
    >
      <div class="editPageStatus" v-if="status">
        当前状态：
        <span v-if="status=='0'">草稿</span>
        <span v-else-if="status=='1'">已启用</span>
        <span v-else-if="status=='2'" class="forbidStatus">已禁用</span>
      </div>
      <editForm
        style="margin-top: 50px"
        :formConfig="editFormConfig"
        ref="basicForm"
        :formData="formData"
      >px</editForm>
    </editPageNew>
  </div>
</template>

<script>
import {
  addEquipmentBackup, // 新增
  updateEqBackup, // 修改保存
  submitEqBackup, // 提交
  deleteEqBackup, // 删除
  getDetails, // 获取详情
  getTree, // 类别,
  getTreeList,
  changeStatusApi //修改状态
} from "@/api/equipmentLedger/equipmentBackup.js";
import {
  serchEqBackup // 查询
} from "@/api/equipmentLedger/equipmentBackup.js";
export default {
  data() {
    return {
      status: "",
      source: "",
      pageType: "",
      classifyId: "",
      equipmentList: [],
      spartStatus: ["1", "2"],
      formData: {},
      treeList: [],
      editFormConfig: {
        itemArr: [
          {
            type: "text",
            label: "备件名称:",
            prop: "name",
            placeholder: "请输入备件名称",
            required: true,
            clearable: true,
            disabled: false,
            span: 8
          },
          {
            type: "text",
            label: "备件编号:",
            prop: "code",
            placeholder: "请输入备件编号",
            clearable: true,
            disabled: false,
            span: 8,
            methods: obj => {
              // 查询编号是否已有
              // pageType为add
              if (obj) {
                this.queryCode(obj);
              }
            }
          },
          {
            type: "select",
            label: "类别:",
            prop: "classifyId",
            placeholder: "请选择类别",
            required: true,
            clearable: true,
            disabled: false,
            span: 8,
            selectOption: [],
            methods: obj => {
              this.classifyId = obj.value;
            }
          },
          {
            type: "text",
            label: "备件型号:",
            prop: "type",
            placeholder: "请输入备件型号",
            required: true,
            clearable: true,
            disabled: false,
            span: 8
          },
          {
            type: "number",
            label: "备件数量:",
            prop: "amount",
            placeholder: "请输入备件备件数量",
            required: true,
            clearable: true,
            disabled: false,
            span: 8
          },
          {
            type: "text",
            label: "计量单位:",
            prop: "unit",
            placeholder: "请输入计量单位",
            required: true,
            span: 8,
            clearable: true,
            disabled: false,
          },
          {
            type: "device-select",
            label: "适用设备:",
            prop: "backApply",
            idsStr: "backApplyId",
            propArr: "backApplyList",
            placeholder: "请选择设备",
            required: true,
            disabled: false,
            trigger: "change",
            span: 16,
            rows: 3,
            option: [],
            multiple: true,
            methods: arr => {
              // 获取选择的设备
              if (arr.length) {
                let list = [];
                arr.map(i => {
                  let obj = {
                    equip_id: i.id,
                    equip_name: i.name,
                    level: i.level,
                    parentId: i.parentId,
                    parentName: i.parentName,
                    sort: i.sort,
                    status: i.status
                  };
                  list.push(obj);
                });
                this.equipmentList = list;
              }
            }
          }
        ]
      }
    };
  },
  created() {
    this.pageType = this.$route.query.pageType;
    this.classifyId = this.$route.query.classifyId;
    getTreeList().then(res => {
      res.data.map(i => {
        this.treeList.push({ label: i.name, value: i.id });
      });
      this.editFormConfig.itemArr[2].selectOption = this.treeList;
      this.treeList.map(i => {
        if (this.classifyId == i.value) {
          this.$refs.basicForm.setFormItem("classifyId", i.value);
        }
      });
    });
    if (this.pageType != "add") {
      this.status = this.$route.query.status;
      this.origin = this.$route.query.origin;
      this.formData.id = this.$route.query.id;
      this.formData.status = this.$route.query.status;
      this.formData.origin = this.$route.query.origin;
      this.getDetails();
    }
  },
  methods: {
    async doSubmit(type) {
      let data = await this.$refs.basicForm.getFormData();
      // 删除所选设备字段
      delete data.classifyId;
      data.backApply = this.equipmentList;
      data.backApplyList = this.equipmentList;
      data.classifyId = this.classifyId;
      // 新建保存
      if (type == "save" && this.pageType == "add") {
        // 新增接口
        data.origin = "manual_entry";
        addEquipmentBackup(data)
          .then(res => {
            this.$utils.updateStorage();
            this.$message.success("操作成功！");
            this.status = res.data[0].status;
            this.formData.id = res.data[0].id;
            this.getDetails();
            setTimeout(() => {
              this.changeRouter();
            }, 500);
          })
          .catch(err => {
            console.log(err);
          });
      } else if (type == "save" && this.pageType == "edit") {
        // 修改保存接口
        if (this.origin == "manual_entry") {
          data.origin = "manual_entry";
        } else {
          data.origin = "system_provision";
        }
        updateEqBackup(data).then(res => {
          this.$utils.updateStorage();
          this.$message.success("操作成功！");
          this.status = res.data[0].status;
          this.formData.id = res.data[0].id;
          this.getDetails();
          // setTimeout(() => {
          //   this.changeRouter();
          // }, 500);
        });
      } else if (type == "submit") {
        // 提交接口
        // 判断数据来源类型
        if (this.origin) {
          if (this.origin == "manual_entry") {
            data.origin = "manual_entry";
          } else {
            data.origin = "system_provision";
          }
        } else {
          data.origin = "manual_entry";
        }
        submitEqBackup(data).then(res => {
          this.$utils.updateStorage();
          this.$message.success("操作成功！");
          this.status = res.data[0].status;
          this.formData.id = res.data[0].id;
          this.getDetails();
          setTimeout(() => {
            this.changeRouter();
          }, 500);
        });
      }
    },
    deleteData() {
      let data = {};
      data.id = this.formData.id;
      data.status = this.status;
      data.classifyId = this.$route.query.classifyId;
      this.$confirm("是否要删除此信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteEqBackup(data).then(res => {
          this.$utils.updateStorage();
          this.$message.success("操作成功");
          this.$refs.editPage.closePage(1000);
        });
      });
    },
    //
    getDetails(id) {
      id = id || this.formData.id;
      getDetails(id).then(res => {
        if (res.data.length) {
          this.status = res.data[0].status;
          this.initForm();
          // 处理适用设备
          let data = JSON.parse(JSON.stringify(res.data[0]));
          let backApply = JSON.parse(JSON.stringify(res.data[0].backApply));
          this.equipmentList = backApply;
          data.backApply = backApply.map(i => i.equip_name).join(", ");
          data.backApplyId = backApply.map(i => i.equip_id).join(", ");
          let backApplyOption = backApply.map(i => {
            let obj = {
              label: i.equip_name,
              value: i.equip_id,
              id: i.equip_id,
              name: i.equip_name
            };
            return obj;
          });
          
          let backApplyList = backApply.map(i => i.equip_id);
          this.$nextTick(() => {
            this.$refs.basicForm.setItemOption("backApply", backApplyOption);
          });
          setTimeout(() => {
            this.$refs.basicForm.setFormItem("backApplyList", backApplyList);
          },100);
          this.formData = data;
        }
      });
    },
    //初始化表格
    initForm() {
      let itemArr = [];
//$.extend(true, itemArr, this.editFormConfig.itemArr);
      let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      this.editFormConfig.itemArr.map(i => {
        if (!haveJurisdiction) {
          i.disabled = true;
        }else{
          if (this.status == "0") {
          i.disabled = false;
        } else if (this.status == "1") {
          if (i.prop == "backApply") {
            i.disabled = false;
          } else {
            i.disabled = true;
          }
        } else if (this.status == "2") {
          i.disabled = true;
        }
        }
      });
      //this.editFormConfig.itemArr = itemArr;
    },
    changeStatus(type) {
      let form = {
        id: this.formData.id,
        status: type
      };
      changeStatusApi(form).then(res => {
        this.$message.success("操作成功！");
        this.getDetails();
      });
    },
    changeRouter() {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
        status: this.status,
        origin: this.origin ? this.origin : "manual_entry",
        classifyId: this.classifyId
      });
      this.$router.push({
        query: obj
      });
    },
    // 查询编号是否存在
    queryCode(code) {
      let oldCode = this.formData.code;
      let data = {
        code: code
      };
      if (oldCode != code) {
        serchEqBackup(data).then(res => {
          if (res.data.list.length) {
            this.$message.warning("备件编号已存在！！！");
          } else {
          }
        });
      }
    }
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide: ["2"].includes(this.status),
          disabled:!this.$store.getters["isBtnAuth"]("edit"),
          content: this.$store.getters["isBtnAuth"]("edit")
            ? null
            : "未授权此功能！",
          methods: () => {
            this.doSubmit("save");
          }
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide: ["1", "2"].includes(this.status),
          disabled:!this.$store.getters["isBtnAuth"]("edit"),
          content: this.$store.getters["isBtnAuth"]("edit")
            ? ""
            : "未授权此功能！",
          methods: () => {
            this.doSubmit("submit");
          }
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide: ["2"].includes(this.status) || ["add"].includes(this.pageType),
          disabled:!this.$store.getters["isBtnAuth"]("delete"),
          content: this.$store.getters["isBtnAuth"]("delete")
            ? ""
            : "未授权此功能！",
          methods: () => {
            this.deleteData();
          }
        },
        {
          text: "停用",
          icon: "el-icon-document-delete",
          hide: ["2"].includes(this.status) || ["add"].includes(this.pageType),
          disabled:!this.$store.getters["isBtnAuth"]("stop"),
          content: this.$store.getters["isBtnAuth"]("stop")
            ? ""
            : "未授权此功能！",
          methods: () => {
            this.changeStatus("2");
          }
        },
        {
          text: "启用",
          icon: "el-icon-document-checked",
          hide: this.status != "2",
          content: this.$store.getters["isBtnAuth"]("start")
            ? ""
            : "未授权此功能！",
          disabled:!this.$store.getters["isBtnAuth"]("start"),
          methods: () => {
            this.changeStatus("1");
          }
        }
      ];
      return arr;
    }
  },
  watch: {
    source: {
      handler(val) {}
    }
  }
};
</script>

<style lang="less" scoped>
.sparePartDetails {
  height: 100%;
  background-color: #ffffff;
  .editPageStatus {
    // background-color: skyblue;
    position: fixed;
    top: 72px;
    span {
      display: inline-block;
      text-align: center;
      padding: 1px 10px;
      width: 50px;
      border-radius: 30px;
      background-color: rgb(122, 182, 3);
      color: white;
    }
    .forbidStatus {
      background-color: rgb(231, 40, 40);
    }
  }
}
</style>